package red.yancloud.www.ui.activity

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONObject
import com.chad.library.adapter.base.BaseQuickAdapter
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_my_collect.*
import kotlinx.android.synthetic.main.title_base_head.*
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jsoup.Jsoup
import red.yancloud.www.R
import red.yancloud.www.base.BaseRefreshActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.common.MessageEvent
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.MyCollect
import red.yancloud.www.ui.adapter.MyCollectRecyclerAdapter
import red.yancloud.www.ui.adapter.RecycleViewDivider
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.ScreenUtils
import red.yancloud.www.util.ToastUtils

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/11 10:49
 * E_Mail：yh131412hys@163.com
 * Describe：我的收藏
 * Change：
 * @Version：V1.0
 */
class MyCollectActivity : BaseRefreshActivity(), View.OnClickListener {

    private val TAG = "MyCollectActivity"

//    private var page: Int = 1
//    private var totalPage: Int = 0
    private lateinit var mRecyclerAdapter: MyCollectRecyclerAdapter

    override val layoutId: Int
        get() = R.layout.activity_my_collect

    override fun initData() {
        super.initData()

        EventBus.getDefault().register(this)
    }

    override fun configViews() {
        super.configViews()

        title_tv.text=intent.getStringExtra("title")

        back_iv.setOnClickListener(this)
    }

//    override fun initView() {
//
//        title_tv.text=intent.getStringExtra("title")
//
//        back_iv.setOnClickListener(this)
//
////        initRecyclerView()
////        initSmartRefreshLayout()
//    }

    override fun getRefreshDataList() {

        loadingDialog.show()

        RedCloudApis.getInstance().myFavorite(
            UserInfoShardPreference.instance.uid,
            page.toString(),
            limit,
            object : Observer<MyCollect> {

                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: MyCollect) {

                    Log.d(TAG,t.toString())

                    if (t.code == Constants.SYSTEM_OK) {

                        if (t.data != null&&t.data.page!=null) {

                            totalPage = t.data.page.totalPage

                            if (t.data.page.count.toInt()==0) {

                                errorView.visibility=View.VISIBLE
                                smartRefreshLayout.visibility=View.GONE
                                loadingDialog.dismiss()
                                return
                            }
                        }

                        if(t.data.records != null && t.data.records.size > 0){

                            if (page==1) {

                                mRecyclerAdapter.clear()
                                mRecyclerAdapter.addData(t.data.records)
                                smartRefreshLayout.resetNoMoreData()
                                smartRefreshLayout.finishRefresh()
                            }else {

                                mRecyclerAdapter.addData(t.data.records)
                                smartRefreshLayout.finishLoadMore()
                            }
                        }else{

                            if (page==1){

                                errorView.visibility=View.VISIBLE
                                smartRefreshLayout.visibility=View.GONE
                                smartRefreshLayout.finishRefresh()
                            }else{

                                ToastUtils.showToast(getString(R.string.data_all_load))
                                smartRefreshLayout.finishLoadMore()
                            }
                        }
                    }else{

                        errorView.visibility=View.VISIBLE
                        smartRefreshLayout.visibility=View.GONE
                    }

                    loadingDialog.dismiss()
                }

                override fun onError(e: Throwable) {

                    loadingDialog.dismiss()
                }
            })
    }

    override fun initRecyclerView() {

        myCollectActivity_rV.layoutManager=LinearLayoutManager(mContext,RecyclerView.VERTICAL,false)
        myCollectActivity_rV.addItemDecoration(RecycleViewDivider(mContext, DividerItemDecoration.VERTICAL,ScreenUtils.dpToPx(10f).toInt(),R.color.color_f5))
        mRecyclerAdapter = MyCollectRecyclerAdapter()
        myCollectActivity_rV.adapter= mRecyclerAdapter
        mRecyclerAdapter.setOnItemClickListener(object :BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                val recordsBean = mRecyclerAdapter.mData[position]
                when (recordsBean.model) {

                    Constants.CollectModel.ZHIKU -> {

                        startActivity(
                            Intent(mContext, NewsInfoActivity::class.java)
                                .putExtra(
                                    "url",
                                    "${Constants.API_BASE_RED_CLOUD_URL}News/entry/?id=${recordsBean.contentId}")
                                .putExtra("model",recordsBean.model)
                                .putExtra("id",recordsBean.contentId.toString())
                        )
                    }
                    Constants.CollectModel.BOOK -> {

                        startActivity(
                            Intent(mContext,BookInfoActivity::class.java)
                            .putExtra("bookId",recordsBean.contentId.toString())
                            .putExtra("url","${Constants.API_BASE_RED_CLOUD_URL}article/?bid=${recordsBean.contentId}"))
                    }
                    Constants.CollectModel.MEDIA -> {

                        if (!TextUtils.isEmpty(recordsBean.content)) {

                            val videoSource = Jsoup.parse(recordsBean.content).select("video").select("source").attr("src")

                            if (!TextUtils.isEmpty(videoSource)) {

                                startActivity(
                                    Intent(mContext, VideoInfoActivity::class.java)
                                        .putExtra("id", recordsBean.contentId.toString())
                                )
                            }
                        }

                        if (!TextUtils.isEmpty(recordsBean.fileaddress)) {

                            if (recordsBean.fileaddress.startsWith("http")) {

                                AppUtils.openBrowser(this@MyCollectActivity,recordsBean.fileaddress)
                            }else{

                                startActivity(
                                    Intent(mContext, VideoInfoActivity::class.java)
                                        .putExtra("id", recordsBean.contentId.toString())
                                )
                            }
                        }

//                        loadingDialog.show()
//
//                        RedCloudApis.getInstance().getVideo(recordsBean.contentId.toString(), object : Observer<VideoInfo> {
//                            override fun onComplete() {
//                            }
//
//                            override fun onSubscribe(d: Disposable) {
//                            }
//
//                            override fun onNext(t: VideoInfo) {
//
//                                if (t.code == Constants.SYSTEM_OK&&t.data!=null&&t.data.video!=null) {
//
//                                    if (!TextUtils.isEmpty(t.data.video.content)) {
//
//                                        val videoSource = Jsoup.parse(t.data.video.content).select("video").select("source").attr("src")
//
//
//                                        if (!TextUtils.isEmpty(videoSource)) {
//
//                                            startActivity(
//                                                Intent(mContext, VideoInfoActivity::class.java)
//                                                    .putExtra("id", recordsBean.contentId.toString())
//                                            )
//                                        }
//                                    }
//
//                                    if (!TextUtils.isEmpty(t.data.video.fileaddress)) {
//
//                                        AppUtils.openBrowser(this@MyCollectActivity,t.data.video.fileaddress)
//                                    }
//                                }
//
//                                loadingDialog.dismiss()
//                            }
//
//                            override fun onError(e: Throwable) {
//
//                                loadingDialog.dismiss()
//                            }
//                        })
                    }
                    Constants.CollectModel.PAINTING -> {

                        startActivity(
                            Intent(mContext, NewsInfoActivity::class.java)
                                .putExtra(
                                    "url",
                                    "${Constants.API_BASE_RED_CLOUD_URL}Article/manhuiindex/?id=${recordsBean.contentId}")
                                .putExtra("model",recordsBean.model)
                                .putExtra("id",recordsBean.contentId.toString())
                        )
                    }
                    Constants.CollectModel.TRAVEL -> {

                        startActivity(
                            Intent(mContext, NewsInfoActivity::class.java)
                                .putExtra(
                                    "url",
                                    "${Constants.API_BASE_RED_CLOUD_URL}News/index?id=${recordsBean.contentId}")
                                .putExtra("model",recordsBean.model)
                                .putExtra("id",recordsBean.contentId.toString())
                        )
                    }
                    Constants.CollectModel.REALLY -> {

                        startActivity(
                            Intent(mContext,NewsInfoActivity::class.java)
                            .putExtra("url","${Constants.API_BASE_RED_CLOUD_URL}News/index?id=${recordsBean.contentId}")
                            .putExtra("model",recordsBean.model)
                            .putExtra("id",recordsBean.contentId.toString())
                        )
                    }
                    Constants.CollectModel.REDSBAG -> {

                        startActivity(
                            Intent(mContext,NewsInfoActivity::class.java)
                            .putExtra("url","${Constants.API_BASE_RED_CLOUD_URL}News/index?id=${recordsBean.contentId}")
                            .putExtra("model",recordsBean.model)
                            .putExtra("id",recordsBean.contentId.toString())
                        )
                    }
                    Constants.CollectModel.SUBJECT -> {

                        startActivity(
                            Intent(mContext, SpecialTopicContentActivity::class.java)
                                .putExtra("id", recordsBean.contentId.toString())
                                .putExtra("introduce", recordsBean.introduce)
                        )
                    }
                    Constants.CollectModel.NEWS -> {

                        /*http://www.yancloud.red/Subject/News/info/id/11840.html*/
                        /*http://www.yancloud.red/Yancloudapp/News/index/id/11840.html*/
                        startActivity(
                            Intent(mContext,NewsInfoActivity::class.java)
                            .putExtra("url","${Constants.API_BASE_RED_CLOUD_URL}News/index?id=${recordsBean.contentId}")
                            .putExtra("model",recordsBean.model)
                            .putExtra("id",recordsBean.contentId.toString())
                        )
                    }
                }
            }
        })
//        mRecyclerAdapter.onItemClickListener=object :BaseQuickAdapter.OnItemClickListener {
//            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
//
//            }
//        }

        mRecyclerAdapter.setonItemChildClickListener(object :BaseQuickAdapter.OnItemChildClickListener {
            override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                RedCloudApis.getInstance().myCollectDelete(UserInfoShardPreference.instance.uid,(mRecyclerAdapter.mData[position] as MyCollect.DataBean.RecordsBean).id,object : Observer<ResponseBody> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: ResponseBody) {

                        val result = String(t.bytes())

                        if (!TextUtils.isEmpty(result)) {

                            val jsonObject = JSONObject.parseObject(result)
                            val code = jsonObject.getString("code")

                            if (code==Constants.SYSTEM_OK) {

                                ToastUtils.showToast(getString(R.string.delete_success))
                                mRecyclerAdapter.remove(position)
                            }else{

                                ToastUtils.showToast(jsonObject.getString("msg"))
                            }
                        }else{

                            ToastUtils.showToast(getString(R.string.delete_failure))
                        }
                    }

                    override fun onError(e: Throwable) {
                    }
                })
            }
        })
//        mRecyclerAdapter.onItemChildClickListener=object :BaseQuickAdapter.OnItemChildClickListener {
//            override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
//
//            }
//        }
    }

//    private fun initSmartRefreshLayout() {
//
//        val mClassicsHeader = smartRefreshLayout.refreshHeader as ClassicsHeader
//        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis()))
//        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
//        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))
//        mClassicsHeader.spinnerStyle = SpinnerStyle.Scale
//
////        smartRefreshLayout.setEnableAutoLoadMore(true)//开启自动加载功能（非必须）
//        smartRefreshLayout.setOnRefreshListener(OnRefreshListener {
//
//            page=1
//            if (!NetworkUtils.isConnected(mContext)) {
//                errorView.visibility = View.VISIBLE
//                ToastUtils.toastNetErrorMsg()
//                smartRefreshLayout.finishRefresh()
//                return@OnRefreshListener
//            }
//            getMyFavoriteList()
//        })
//        smartRefreshLayout.setOnLoadMoreListener(OnLoadMoreListener { refreshLayout ->
//
//            if (page>=totalPage){
//
//                ToastUtils.showToast(getString(R.string.data_all_load))
//                smartRefreshLayout.finishLoadMoreWithNoMoreData()//将不会再次触发加载更多事件
//                return@OnLoadMoreListener
//            }
//
//            if (!NetworkUtils.isConnected(mContext)) {
//                errorView.visibility = View.VISIBLE
//                ToastUtils.toastNetErrorMsg()
//                smartRefreshLayout.finishLoadMore()
//                page=1
//                return@OnLoadMoreListener
//            }
//            page++
//            getMyFavoriteList()
//        })
//    }

    override fun onClick(v: View?) {
        when (v!!.id) {
             R.id.back_iv-> finish()
            else -> {
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent){

        when (event.type) {
            Constants.REFRESH_MY_COLLECT-> {

                Log.d(TAG,event.type.toString())
                page = 1
                getRefreshDataList()
            }
        }
    }
}
